import {
  HocuspocusProvider,
  HocuspocusProviderWebsocket,
} from '@hocuspocus/provider';
import type { Awareness } from 'y-protocols/awareness';
import * as Y from 'yjs';

const CollaborationUrl = `ws://localhost:4333`;

export class CollaborationServerProvider {
  private _websocket: HocuspocusProviderWebsocket;
  public provider: HocuspocusProvider;
  public whenReady: Promise<void>;

  constructor(
    documentId: string,
    doc: Y.Doc,
    public readonly awareness: Awareness,
    public readonly token: string,
    public readonly user: { id: string; name: string }
  ) {
    this._websocket = new HocuspocusProviderWebsocket({
      url: CollaborationUrl,
    });

    this.provider = new HocuspocusProvider({
      websocketProvider: this._websocket,
      name: documentId,
      document: doc,
      token,
      awareness,
    });

    this.provider.setAwarenessField('user', {
      name: this.user.name,
      id: this.user.id,
    });

    if (this.provider.isSynced) {
      this.whenReady = Promise.resolve();
    } else {
      this.whenReady = new Promise((resolve) => {
        const fn = () => {
          this.provider.off('synced', fn);
          resolve();
        };
        this.provider.on('synced', fn);
      });
    }
  }

  cleanup() {
    this.provider.destroy();
    this._websocket.destroy();
  }
}